<template>
  <div id="newDetailNum" class="text-white">
    <template v-if="rechargePlatformConfig.length">
      <h2 class="hairline-bottom mb-4 pb-3 text-base uppercase">{{ $mt('Recharge information') }}</h2>
      <section class="mb-5 grid grid-cols-1 gap-y-3">
        <div v-for="item in rechargePlatformConfig">
          <div class="mb-2 flex items-center text-white1">
            {{ item.name }}
            <div v-if="item.tipImage" class="flex cursor-pointer" @click="showTipImage(item.tipImage)">
              <div class="anime-swing ml-2 h-4 w-4 rounded-full bg-[#007aff]">
                <WImage :src="useAsset('goods-question')" />
              </div>
              <span class="ml-1 text-xs text-gray-light">Click</span>
            </div>
          </div>
          <select
            v-if="item.selected"
            v-model="item.value"
            class="select select-sm select-info w-3/5 max-w-xs rounded-sm bg-black"
            :class="{ 'select-error': !item.value }">
            <option disabled selected :value="null">{{ item.tip }}</option>
            <option :value="sub" v-for="sub in item.values">{{ sub.name }}</option>
          </select>
          <template v-else>
            <input
              type="text"
              autocomplete="off"
              name="uniqueName3"
              id="uniqueId3"
              v-model.trim="item.value"
              :placeholder="item.tip"
              class="input input-sm input-bordered input-info w-full max-w-xs rounded-sm bg-black"
              :class="item.value ? '' : 'select-error'" />
          </template>
        </div>
      </section>
    </template>
    <!-- title -->
    <div @click="showBottom = true" class="mb-4 flex items-center lg:hidden">
      <strong class="mr-2 text-base">{{ $mt('Select Denomination') }}</strong>
      <w-image class="ml-auto h-3.5 w-3.5" :src="useAsset('detail/item_icon_arrow.png')" />
    </div>
    <!-- title -->
    <!-- 当前的 sku  -->
    <div @click="showBottom = true" class="mb-4 flex rounded-md bg-[#393d3e] px-2.5 py-3 lg:hidden">
      <div class="w-12 shrink-0 rounded-lg ltr:mr-3 rtl:ml-3">
        <YImage
          class="product-poster--small mx-auto h-12 rounded-lg object-cover"
          :alt="`${$mt('how to recharge')} ${curGoodsDetail.name} ${curGoodsSkuInfo.name}`"
          :src="curGoodsSkuInfo.smallIcon || curGoodsDetail.smallIcon"
          width="50"
          height="50" />
      </div>
      <div>
        <h3 class="mb-2.5 text-sm font-bold">
          {{ curGoodsDetail.isWalletPurchaseGoods ? $calcPrice(curGoodsSkuInfo.price) : curGoodsSkuInfo.name }}
        </h3>
        <div class="flex items-center text-sm">
          <p class="font-bold text-red1 ltr:mr-2 rtl:ml-2">{{ $calcPrice(curGoodsSkuInfo.price) }}</p>
          <p class="text-[rgba(255,255,255,0.5)] line-through" v-if="curGoodsSkuInfo.discount">
            {{ $calcPrice(curGoodsSkuInfo.originalPrice) }}
          </p>
        </div>
      </div>
    </div>
    <!-- 数量 -->
    <div
      v-if="!(curGoodsSkuInfo.minLimit === 1 && curGoodsSkuInfo.maxLimit === 1)"
      class="mx-auto mb-3 box-border flex items-center justify-between border-b-[.5px] border-b-[rgba(255,255,255,0.2)] pb-4">
      <p class="text-base">{{ $mt('Quantity') }}</p>
      <van-stepper
        @overlimit="handleOverLimit"
        :min="curGoodsSkuInfo.minLimit ? curGoodsSkuInfo.minLimit : 1"
        :max="curGoodsSkuInfo.maxLimit ? curGoodsSkuInfo.maxLimit : 10000"
        integer
        class="rounded-md bg-[#393d3e] px-1.5 py-1"
        v-model="buyNum" />
    </div>
    <!-- 总数和支付按钮 -->
    <div class="box-border flex items-end justify-between text-white lg:block lg:items-center">
      <div class="lg:mb-5 lg:mt-6 lg:px-3">
        <div class="items-center justify-between lg:flex">
          <p class="text-sm text-[rgba(255,255,255,0.6)] lg:text-xl">{{ $mt('Total') }}</p>
          <p class="break-all text-xl">{{ $calcPrice(buyNum * curGoodsSkuInfo.price) }}</p>
        </div>
        <p class="text-sm text-[#9acd32] lg:text-base" v-if="curGoodsSkuInfo.discount">
          {{ $mt('Discount') }}: {{ $calcDiscount(curGoodsSkuInfo.discount) }}
        </p>
      </div>
      <!-- 提交订单 -->
      <button
        name="button"
        :disabled="!curGoodsSkuInfo?.id"
        @click="handleSubmitOrder"
        class="flex min-h-12 min-w-[131px] shrink-0 flex-col items-center justify-center rounded-lg bg-red1 px-2 py-0.5 text-white disabled:bg-gray-400 lg:mx-auto lg:w-full lg:rounded-xl">
        <span class="text-center text-base uppercase">
          {{
            curGoodsSkuInfo?.id
              ? curGoodsDetail.isWalletPurchaseGoods
                ? $mt('Recharge Now')
                : $mt('Buy Now')
              : $mt('Sold Out')
          }}
        </span>
        <span class="-mt-1 text-center text-xs text-[#9cdb1c]" v-if="buyNum > 1">Count x {{ buyNum }}</span>
      </button>
    </div>
  </div>
  <DelayHydration>
    <DetailGoodsListPopup class="lg:hidden" v-model="showBottom" />
    <van-image-preview
      :show-index="false"
      @click.native="$isPcScreen() && (showImageVisible = false)"
      v-model:show="showImageVisible"
      :images="previewImages" />
  </DelayHydration>
  <!-- 遮罩层 -->
</template>

<script setup lang="ts">
import YImage from '~/components/logic/YImage.vue'
import WImage from '~/components/logic/WImage.vue'
import { useGoodsStore } from '~/store/goods'
import { goodsPlayerIdIsInValid } from '~/composables/useLogic'
import { safeJsonStringify } from '~/utils'

const { $mt } = useCommonPlugin()
const buyNum = ref(1)
const goodsStore = useGoodsStore()
const { $pushRoute } = useCommonPlugin()
const { curGoodsSkuInfo, curGoodsDetail } = storeToRefs(goodsStore)
const platformConfig = curGoodsDetail.value?.platformConfig || {}
const rechargeInfoCacheKey = JSON.stringify(platformConfig).replace(/\s+/g, '').replace(/\\n+/g, '')
const rechargePlatformConfig = useLocalStorage(`goods-new-${curGoodsDetail.value.id}-${rechargeInfoCacheKey}`, [])

// const PreOrderCacheNew = useLocalStorage('PreOrderCacheNew', {})

function useGoodsViewSetup() {
  const showBottom = ref(false)
  const showImageVisible = ref(false)
  const previewImages = ref([])
  // 根据商品配置模板设置输入框
  watchEffect(() => {
    if (rechargePlatformConfig.value.length) return
    let newConfig = []
    try {
      newConfig = typeof platformConfig === 'string' ? JSON.parse(platformConfig) : []
    } catch (e) {}
    rechargePlatformConfig.value = JSON.parse(JSON.stringify(newConfig))
  })
  // 设置商品最小购买数量 当有sku信息时设置默认购买数量
  watch(
    () => curGoodsSkuInfo.value,
    () => (buyNum.value = curGoodsSkuInfo.value?.minLimit || 1),
    { immediate: true },
  )
  const showTipImage = (imageSrc) => {
    showImageVisible.value = true
    previewImages.value = [imageSrc]
  }
  return {
    showTipImage,
    showBottom,
    showImageVisible,
    previewImages,
  }
}

function useGoodsFormApi() {
  // 处理提交订单 先进行数据校验
  const handleSubmitOrder = async () => {
    const isFormFilled = rechargePlatformConfig.value.some((item) => !item.value)
    // 校验是否填写
    if (isFormFilled) {
      showToast($mt('Please fill in the recharge information'))
      return document.documentElement.scrollTo({ top: 0, behavior: 'smooth' })
    }
    // 跳转到收银台之前先进行判断id  有 isCheckPlayerId 字段才会校验 手动设置一些校验规则
    if (
      curGoodsDetail.value.isCheckPlayerId &&
      goodsPlayerIdIsInValid(curGoodsDetail.value.id, rechargePlatformConfig)
    ) {
      return showDialog({
        message: $mt('Your Player ID is wrong. Please check the product details and fill in the correct ID'),
        title: $mt('WARNING'),
        confirmButtonText: $mt('Confirm'),
      })
    }
    // 缓存订单信息
    const queryCurGoodsDetail = Object.entries(unref(curGoodsDetail)).reduce((acc, [key, val]) => {
      if (typeof val === 'object' || key === 'content') return acc
      acc[key] = val
      return acc
    }, {})
    localStorage.setItem(
      `PreOrderCacheNew-${curGoodsSkuInfo.value.id}`,
      safeJsonStringify({
        curGoodsSkuInfo: unref(curGoodsSkuInfo),
        curGoodsDetail: queryCurGoodsDetail,
        rechargePlatformConfig: unref(rechargePlatformConfig),
      }),
    )
    localStorage.setItem('cachedSkuId', curGoodsSkuInfo.value.id)
    return $pushRoute({
      path: '/pre-order',
      query: {
        goodsSkuId: curGoodsSkuInfo.value.id,
        count: buyNum.value,
      },
    })
  }
  // 数量超出限制提示
  const handleOverLimit = (val) => {
    if (val === 'minus') {
      showConfirmDialog({
        title: $mt('Notice'),
        message: `${$mt('Minimum purchase of')} ${curGoodsSkuInfo.value.minLimit} ${$mt('items')}`,
        showCancelButton: false,
        confirmButtonText: 'OK',
      })
      return
    }
    showConfirmDialog({
      title: $mt('Notice'),
      message: `${$mt('Maximum purchase of')} ${curGoodsSkuInfo.value.maxLimit} ${$mt('items')}`,
      showCancelButton: false,
      confirmButtonText: 'OK',
    })
  }
  return {
    handleSubmitOrder,
    handleOverLimit,
  }
}

const { showTipImage, showBottom, showImageVisible, previewImages } = useGoodsViewSetup()
const { handleSubmitOrder, handleOverLimit } = useGoodsFormApi()
onMounted(async () => {
  // 触发输入框的更新样式 如果没有这串代码的话 自动填充的充值信息不能更新样式
  const oldData = rechargePlatformConfig.value
  rechargePlatformConfig.value = []
  await nextTick()
  rechargePlatformConfig.value = oldData
})
</script>
<style>
body {
  --van-dialog-has-title-message-text-color: #dadada;
  --van-dialog-transition: 0s;
}
</style>
<style lang="scss">
#newDetailNum {
  .van-dialog {
    background-color: #232728 !important;
  }

  .van-popup {
    background-color: #232728 !important;
  }

  .van-button--default {
    background-color: #232728 !important;
  }

  .van-stepper__input {
    color: #fff;
    background-color: unset;
    font-size: 12px;
  }

  .van-stepper__minus,
  .van-stepper__plus {
    background-color: unset;
    font-size: 12px;
    color: #fff;
  }

  .van-stepper__plus {
    background-color: unset;
    color: #fff;
    font-size: 16px;
  }
}

@keyframes swing-anime {
  from {
    transform: rotateZ(-5deg);
  }
  to {
    transform: rotateZ(5deg);
  }
}

.anime-swing {
  transform-origin: center bottom;
  animation: swing-anime infinite linear alternate 0.4s;
}
</style>
